//
//  AVPlaySingle.m
//  UI_Project_A
//
//  Created by GH on 16/3/8.
//  Copyright © 2016年 GH. All rights reserved.
//

#import "AVPlaySingle.h"


#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@implementation AVPlaySingle




+ (instancetype)playerShare {


    static AVPlaySingle *player = nil;
    static dispatch_once_t predicate;
    
    
dispatch_once(&predicate, ^{
    
    
    player = [[AVPlaySingle alloc] init];
});

    return player;
}


- (void) dealloc {
    
    
    [_playerItem release];
    [_playerLayer release];
    [_player release];
    [_timeLabel release];
    [_playerButton release];
    [_ProgressSlider release];
    [_bottomView release];
    [_playerView release];
    [_viewOftemp release];
    [super dealloc];
    
}




- (instancetype) init {

    self = [super init];
    if (self) {
        self.player = [AVPlayer playerWithPlayerItem:self.playerItem];

    }



    return self;

}



//  播放页面添加轻拍手势
- (void)addGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    
    
    [self.playerView addGestureRecognizer:tap];
}

//隐藏bottomView
-(void)dismissAllSubViews {
    
    if (self.isTap == NO) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bottomView.alpha = 0;
            
        }];
    }else
    {
        [UIView animateWithDuration:0.5 animations:^{
            
            
            self.bottomView.alpha = 0.5;
            
        }];
    }
    self.isTap = !self.isTap;
}





#pragma mark -  添加进度观察 - addProgressObserver
- (void)addProgressObserver {
    
    __block AVPlaySingle *vc = self;
    
    
    [vc.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        
        //当前时间
        CGFloat current = CMTimeGetSeconds(self.playerItem.currentTime);
        
        
        //倒计时
        //        CGFloat rem = duration - current;
        
        //        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *alltime = [NSString stringWithFormat:@"%02d:%02d",(int)duration/60,(int)duration%60];
        
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,alltime];
        
        
        self.timeLabel.text = timeStr;
        
        //保存总时长用于手动快进和快退
        self.totalMovieDuration = duration;
        
        
        //设置进度值 当前时间/总时长
        self.ProgressSlider.value = current/duration;
        
        
    }];
    
    
}






- (void)playerWtihUrl:(NSString *)url showInview:(UIView *)showview {

    //playerview
   
    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/3+20)];
    [showview addSubview:self.playerView];
    [self.playerView release];
    self.playerView.userInteractionEnabled = YES;

    

   // slider
    self.ProgressSlider = [[UISlider alloc]initWithFrame:CGRectMake(45, HEIGHT / 3 - 35, WIDTH - 190, 40)];
    [self.playerView addSubview:self.ProgressSlider];
    [self.ProgressSlider release];
    [self.ProgressSlider addTarget:self action:@selector(moveSlider:) forControlEvents:UIControlEventValueChanged];
    
    
    //button
    self.playerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playerButton.frame = CGRectMake(10, HEIGHT / 3 - 30, 30, 30);
    [self.playerView addSubview:self.playerButton];
    [self.playerButton release];
    
    [self.playerButton setImage:[UIImage imageNamed:@"zanting2"] forState:UIControlStateNormal];
    
    
    [self.playerButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    
    //label
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 150, HEIGHT/3 - 35, 110, 40)];
    [self.playerView addSubview:self.timeLabel];
    [self.timeLabel release];
    self.timeLabel.text = @"00:00/00:00";
    self.timeLabel.textAlignment = 1;
    self.timeLabel.textColor = [UIColor whiteColor];
    
    
    self.buttonFullscreen = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonFullscreen.frame = CGRectMake(WIDTH - 40, HEIGHT/3 - 30, 30, 30);
    
    [self.buttonFullscreen setImage:[UIImage imageNamed:@"quanping"] forState:UIControlStateNormal];
    [self.buttonFullscreen release];
    [self.playerView addSubview:self.buttonFullscreen];
    
    [self.buttonFullscreen addTarget:self action:@selector(fullScreen:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.buttonOfback = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playerView addSubview:self.buttonOfback];
    self.buttonOfback.frame = CGRectMake(10, 10, 50, 50);
    [self.buttonOfback setImage:[UIImage imageNamed:@"jiantou3"] forState:UIControlStateNormal];
    
    [self.buttonOfback addTarget:self action:@selector(handleClieck) forControlEvents:UIControlEventTouchUpInside];
    
    
    
  
    
    //addplayer
    url =[url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *urlstr =[NSURL URLWithString:url];
    
    //创建视频项目对象/ /mµ
    self.playerItem = [[AVPlayerItem alloc] initWithURL:urlstr];
    
    //创建视频播放器对象
//    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    
    
    
    //创建承载播放器的AVPlayerLayer对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, self.playerView.frame.size.height);
    
    
    //视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    //将播放器添加到playerView的layer层上
    [self.playerView.layer insertSublayer:self.playerLayer atIndex:0];
    
    
    
    self.playerView.backgroundColor = [UIColor whiteColor];
    
    
    [self addGestureRecognizer];
    [self addProgressObserver];

    [self addNotificationCenters];
    
    [self.player play];

}

- (void)handleClieck {

    
    [self.player pause];
//
    [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonclick" object:nil];
    
}



#pragma 点击横屏

- (void)fullScreen:(UIButton *)button {
    
    self.isScale = !self.isScale;
    if (self.isScale) {
        
        
        //横屏
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
        {
            [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)UIInterfaceOrientationLandscapeRight];
            
            
            self.ProgressSlider.frame = CGRectMake(50, HEIGHT - 45,WIDTH - 210, 40);
            
            self.playerButton.frame = CGRectMake(10, HEIGHT - 45, 40, 40);
            self.buttonFullscreen.frame = CGRectMake(WIDTH - 45, HEIGHT - 45, 40, 40);
            self.timeLabel.frame = CGRectMake(WIDTH - 160, HEIGHT - 45, 110, 40);
            
            
        }
    }else {
        
        //竖屏
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
        {
            [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)UIInterfaceOrientationPortrait];
        }
        
        
        self.ProgressSlider.frame = CGRectMake(45, HEIGHT / 3 - 35, WIDTH - 190, 40);
        self.playerButton.frame = CGRectMake(10, HEIGHT / 3 - 30, 30, 30);
        self.buttonFullscreen.frame = CGRectMake(WIDTH - 40, HEIGHT/3 - 30, 30, 30);
        
        self.timeLabel.frame = CGRectMake(WIDTH - 150, HEIGHT / 3 - 35, 110, 40);
        
    }
    //
}





- (void)clickButton:(UIButton *)button {
    
    
    if (self.isPlay) {
        [self.player pause];
        [self.playerButton setImage:[UIImage imageNamed:@"fang"] forState:UIControlStateNormal];
    }else
    {
        [self.player play];
        [self.playerButton setImage:[UIImage imageNamed:@"zanting2"] forState:UIControlStateNormal];
    }
    self.isPlay = !self.isPlay;
    
    
    
    
}


- (void)moveSlider:(UISlider *)slider {
    
    //获取当前时间
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
    
}




#pragma mark - 观察者 观察播放完毕 观察屏幕旋转

- (void)addNotificationCenters {
    //  注册观察者用来观察，是否播放完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    //  注册观察者来观察屏幕的旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark - 横屏 竖屏的时候frame的设置
- (void)statusBarOrientationChange:(NSNotification *)notification {
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (orientation == UIInterfaceOrientationLandscapeRight) {
        
        NSLog(@"向右横屏");
        [self setPlayerLayerFrame];
    }
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
        
        NSLog(@"向左横屏");
        [self setPlayerLayerFrame];
        
    }
    if (orientation == UIInterfaceOrientationPortrait) {
        
        NSLog(@"竖屏");
        [self setVerticalFrame];
    }
}

//  横屏的时候frame
- (void)setPlayerLayerFrame {
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    self.playerView.frame = CGRectMake(0, 0,WIDTH, HEIGHT);
    
}

//  竖屏的时候frame
- (void)setVerticalFrame {
    
    self.playerLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT/3+20);
    self.playerView.frame = CGRectMake(0, 0, WIDTH, HEIGHT/3+20);
}



#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify {
    
    NSLog(@"播放结束触发");
    
}






@end
